from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from .models import Article, Category
from comment.forms import CommentForm

import markdown

# Create your views here.


def index(request):
    post = Article.objects.all()
    page_article_count = 4               # 每页显示的文章数
    paginator = Paginator(post, page_article_count)

    page_num = request.GET.get('page')  # 获取页码
    try:
        post = paginator.page(page_num)    # 获取对应页码的记录
    except PageNotAnInteger:                # 如果页码不是整数
        post = paginator.page(1)            # 返回第一页的记录
    except EmptyPage:                       # 如果页码太大， 没有对应记录
        post = paginator.page(paginator.num_pages)  # 返回最后一页

    return render(request, 'index.html', {'post': post})


def detail(request, article_id):
    article = Article.objects.get(id=article_id)
    article.increase_views()                        # 阅读量 +1
    article.content = markdown.markdown(article.content,
                                        extensions=[
                                            'markdown.extensions.extra',
                                            'markdown.extensions.codehilite',
                                            'markdown.extensions.toc',
                                        ])
    form = CommentForm()
    comment_list = article.comment_set.all()
    return render(request, 'detail.html', {'article': article,
                                           'form': form, 'comment_list': comment_list})


def category(request, category_id):
    category_m = Category.objects.get(id=category_id)
    article_category = Article.objects.filter(category=category_m)
    return render(request, 'index.html', {'post': article_category})


def archives(reqeust, year, month):
    article_date = Article.objects.filter(add_time__year=year, add_time__month=month)
    return render(reqeust, 'index.html', {'post': article_date})


def about(request):
    return render(request, 'about.html')


